import { ref, defineComponent, onMounted, warn } from 'vue';
import { Search, Plus, Minus, CheckChecked, DownArrow,ArrowRight } from '@nutui/icons-vue';
import { getCatalogTree } from '@/api/catalog';
import styles from './HomePage.module.less';

export default defineComponent({
  name: 'HomePage',
  setup() {
    const searchText = ref('');
    const expandedNodes = ref(new Set());
    // 保存搜索前的展开状态，用于恢复
    const originalExpandedNodes = ref(new Set());
    // 添加控制分类目录展开/关闭的状态
    const categoryData = ref(window.meunData || []);
    const loading = ref(false)
    
    // 搜索函数
    const onSearch = (value) => {
      
      if (!value.trim()) {
        // 搜索框为空，恢复到搜索前的展开状态
        expandedNodes.value = new Set(originalExpandedNodes.value);
        // 恢复分类的展开状态
        categoryData.value.forEach(category => {
          category.isCategoryExpanded = category.originalExpandedState;
        });
        return;
      }
      
      // 搜索框有内容，保存当前展开状态，用于后续恢复
      if (originalExpandedNodes.value.size === 0) {
        originalExpandedNodes.value = new Set(expandedNodes.value);
        // 保存分类的展开状态
        categoryData.value.forEach(category => {
          category.originalExpandedState = category.isCategoryExpanded;
        });
      }
      
      // 清空当前展开状态，准备根据搜索结果重新展开
      expandedNodes.value = new Set();
      
      // 递归查找包含搜索关键字的节点并展开其所有父级
      categoryData.value.forEach(category => {
        const hasMatchedNode = findAndExpandMatchingNodes(category.children, value);
        if (hasMatchedNode) {
          category.isCategoryExpanded = true;
        }
      });
    };
    
    // 递归查找匹配的节点并展开其所有父级
    const findAndExpandMatchingNodes = (nodes, searchValue) => {
      if (!nodes || nodes.length === 0) return false;
      
      let hasMatched = false;
      
      for (const node of nodes) {
        // 检查当前节点是否匹配搜索关键字
        const isMatch = node.name && node.name.toLowerCase().includes(searchValue.toLowerCase());
        
        // 递归检查子节点
        const childHasMatch = findAndExpandMatchingNodes(node.children, searchValue);
        
        if (isMatch || childHasMatch) {
          // 如果当前节点或其子节点匹配，展开当前节点
          expandedNodes.value.add(node.id);
          hasMatched = true;
        }
      }
      
      return hasMatched;
    };

    const initPage = async function () {
      loading.value = true
      // 循环window.meunData并通过getByCatalogId查询子级
      await loadMenuChildren()
      console.log("页面初始化完成，菜单数据已加载")
      loading.value = false
    }

    // 加载菜单子级数据
    const loadMenuChildren = async function () {
      console.warn(`开始加载菜单子级数`,categoryData.value);
      
      // 循环meunData并通过getByCatalogId查询每个菜单的子级
      for (let i = 0; i < categoryData.value.length; i++) {
         const categoryItem = categoryData.value[i]
        try {
          const response = await getCatalogTree(categoryItem.menuId)
           console.warn("aaa",response.data.data);
          // 将子级数据存储在菜单对象中
          if (response.data.code === 0) {
            categoryItem.children = response.data.data.children
            categoryItem.isCategoryExpanded = false
            // 初始化原始展开状态
            categoryItem.originalExpandedState = false
          } else {
            categoryItem.children = []
          }
        } catch (error) {
          categoryItem.children = []
        }
      }
      warn(`完成加载菜单子级数`,categoryData.value);
    }

    initPage()
    // 切换节点展开/折叠状态
    const toggleNode = (nodeId) => {
      if (expandedNodes.value.has(nodeId)) {
        expandedNodes.value.delete(nodeId);
      } else {
        expandedNodes.value.add(nodeId);
      }
    };

    // 切换分类目录展开/折叠状态
    const toggleCategory = (categoryItem) => {
      // 切换特定分类项的展开状态
      categoryItem.isCategoryExpanded = !categoryItem.isCategoryExpanded;
      // 如果不在搜索状态，更新原始状态
      if (!searchText.value.trim()) {
        categoryItem.originalExpandedState = categoryItem.isCategoryExpanded;
      }
    };

    // 检查节点是否展开
    const isNodeExpanded = (nodeId) => {
      return expandedNodes.value.has(nodeId);
    };

    // 递归渲染分类树
    const renderCatalogTree = (nodes, depth = 0) => {
      return nodes.map(node => {
        const hasChildren = node.children && node.children.length > 0;
        const isExpanded = isNodeExpanded(node.id);

        // 处理文本高亮显示
        const renderHighlightedText = (text) => {
          if (!searchText.value.trim() || !text) {
            return text;
          }
          
          const searchValue = searchText.value.toLowerCase();
          const lowerText = text.toLowerCase();
          const index = lowerText.indexOf(searchValue);
          
          if (index === -1) {
            return text;
          }
          
          const beforeMatch = text.substring(0, index);
          const match = text.substring(index, index + searchValue.length);
          const afterMatch = text.substring(index + searchValue.length);
          
          return (
            <>
              {beforeMatch}
              <span class={styles.highlight}>{match}</span>
              {afterMatch}
            </>
          );
        };

        return (
          <div
            key={node.id}
            class={`${styles.catalogItem} ${!hasChildren ? styles.noChildren : ''} ${depth > 0 ? styles.depth : ''}`}
          >
            <div
              class={`${styles.catalogItemHeader} ${depth > 0 && isExpanded ? styles.expanded : ''}`}
              onClick={hasChildren ? () => toggleNode(node.id) : undefined}
            >

              {hasChildren && (
                isExpanded ?
                  <div class={styles.icon}><Minus size="16" /></div> :
                  <div class={styles.icon}><Plus size="16" /></div>
              )}
              <div class={styles.catalogItemName}>
                <span>{renderHighlightedText(node.name)}</span>
                <div class={styles.catalogItemNameIcon}><ArrowRight size="16" /></div>
              </div>
              
            </div>
            {hasChildren && isExpanded && (
              <div class={styles.catalogChildren}>
                {renderCatalogTree(node.children, depth + 1)}
              </div>
            )}
          </div>
        );
      });
    };

    return () => (
      <div class={styles.home}>
        <nut-navbar
          title="药知晓"
        >
        </nut-navbar>
        <div class={styles.searchContainer}>
          <nut-searchbar v-model={searchText.value} onChange={onSearch}>
            {{
              leftin: () => <Search class={styles.searchIcon} size="18" />
            }}
          </nut-searchbar>
        </div>
        <div class={styles.categoryContainer}>
          {categoryData.value.map(categoryItem =>
            <div class={styles.categoryItem} key={categoryItem.menuId}>
            <div
              class={styles.categoryTitle}
              onClick={() => toggleCategory(categoryItem)} 
            >
              <div class={styles.categoryTitleContent}>
                <div class={styles.categoryIcon}>
                  <CheckChecked />
                </div>
                {categoryItem.meunTitle}
              </div>
              <DownArrow
                size="5px"
              />
            </div>
              {categoryItem.children && categoryItem.isCategoryExpanded && <div class={styles.categoryContent}>
                {renderCatalogTree(categoryItem.children)}
              </div>}
            </div>
          )}
        </div>
      </div>
    );
  }
});